package com.jsmile.cloud.authc.sys.repo;

import java.util.List;
import java.util.Objects;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsmile.cloud.authc.api.req.sys.ReqSysDeptPageQuery;
import com.jsmile.cloud.authc.api.req.sys.ReqSysDeptQuery;
import com.jsmile.cloud.authc.sys.dao.SysDepartmentDao;
import com.jsmile.cloud.authc.sys.model.SysDepartment;
import com.jsmile.mall.api.kit.DateKit;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 龚亮
 * @version 1.0
 * @desc 为了薪资破万，还是睡一会儿吧...!
 * @date 2020年10月16日 02:46:20
 */
@Service
@Slf4j
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class SysDepartmentSearchRepository extends ServiceImpl<SysDepartmentDao, SysDepartment> {

    public IPage<SysDepartment> pageQuery(ReqSysDeptPageQuery reqSysDeptPageQuery) {
        return this.baseMapper.selectPage(reqSysDeptPageQuery.getPage(), getQueryWrapper(reqSysDeptPageQuery));
    }

    public List<SysDepartment> getList(ReqSysDeptQuery reqSysDeptQuery) {
        return this.baseMapper.selectList(getQueryWrapper(BeanUtil.toBean(reqSysDeptQuery, ReqSysDeptPageQuery.class)));
    }

    private Wrapper getQueryWrapper(ReqSysDeptPageQuery reqSysDeptQuery) {
        return new QueryWrapper<SysDepartment>().lambda().eq(null != reqSysDeptQuery.getCurTenantId(), SysDepartment::getTenantId, reqSysDeptQuery.getCurTenantId())
            .like(Objects.nonNull(reqSysDeptQuery.getDeptName()), SysDepartment::getDeptName, reqSysDeptQuery.getDeptName())
            .eq(null != reqSysDeptQuery.getDeptType(), SysDepartment::getDeptType, reqSysDeptQuery.getDeptType())
            .eq(null != reqSysDeptQuery.getParentId(), SysDepartment::getParentId, reqSysDeptQuery.getParentId())
            .ge(null != reqSysDeptQuery.getStartDate(), SysDepartment::getCreateTime, DateKit.beginOfDay(reqSysDeptQuery.getStartDate()))
            .le(null != reqSysDeptQuery.getEndDate(), SysDepartment::getCreateTime, DateKit.endOfDay(reqSysDeptQuery.getEndDate())).orderByDesc(SysDepartment::getCreateTime);// sort,createTime倒序
    }
}
